<?php

namespace Framework;

use Illuminate\Http\Exceptions\HttpResponseException;
use InvalidArgumentException;
use Symfony\Component\HttpKernel\Exception\HttpException;

trait ErrorHelper
{
    public function retError(
        $error,
        int $code = 400,
        array $data = null,
        array $headers = []
    ) {
        if (is_string($error)) {
            $error = new ErrorResponse($error, $code, $data);
        }

        if (! ($error instanceof ErrorResponse)) {
            throw new InvalidArgumentException('error must instanceof ErrorResponse');
        }

        throw new HttpResponseException(response($error, 400, $headers));
    }

    public function errorNotFound(string $message = 'Not Found')
    {
        throw new HttpResponseException(response(new ErrorResponse($message, 404), 404));
    }

    public function errorUnauthorized()
    {
        throw new HttpResponseException(response(new ErrorResponse('Unauthorized', 401), 401));
    }

    public function errorDataError()
    {
        throw new HttpException(421, 'data error!!!');
    }

    public function getAmountInt($amount): int
    {
        return floor($amount * 100000000);
    }

    public function getAmountDisplay(int $amount): string
    {
        return bcdiv($amount, 100000000, 8);
    }

    /**
     * 系统繁忙.
     */
    protected function errorBusy(string $message = null)
    {
        throw new HttpException(420, '系统繁忙');
    }
}
